import { Injectable } from "@angular/core";
import { LSPMessageFactory } from "../LSP/LSPMessageFactory";

@Injectable({
  providedIn: "root"
})
export class WebSocketService {
  constructor() {}
  sendMessage(ws, messageId, frame) {
    let sframe = JSON.stringify(frame);
    let message;
    let sendFlag = true;
    let i = 0;
    let that = this;
    let interval1 = setInterval(function() {
      if (i > sframe.length) {
        clearInterval(interval1);
      } else if (sendFlag) {
        sendFlag = false;
        let frameId = 0;
        if (sframe.length > i + 5000) {
          message = LSPMessageFactory.getLSPMessage(
            messageId,
            frameId++,
            false,
            sframe.substring(i, i + 5000)
          );
        } else {
          message = LSPMessageFactory.getLSPMessage(
            messageId,
            frameId++,
            true,
            sframe.substring(i)
          );
        }
        let interval = setInterval(function() {
          if (ws.readyState == WebSocket.OPEN) {
            clearInterval(interval);
            console.log(message);
            ws.send(JSON.stringify(message));
            sendFlag = true;
            i += 5000;
          } else if (ws.readyState == WebSocket.CLOSED) {
            console.log("diagram.ws.readyState=CLOSED ", ws.readyState);
          } else if (ws.readyState == WebSocket.CLOSING) {
            console.log("diagram.ws.readyState=CLOSING ", ws.readyState);
          } else if (ws.readyState == WebSocket.CONNECTING) {
            console.log("diagram.ws.readyState=CONNECTING ", ws.readyState);
          }
        }, 80);
      }
    }, 100);
  }
}
